import {
  Button,
  Card,
  DatePicker,
  Icon,
  Input,
  InputNumber,
  message,
  Select,
  Spin,
  Table,
  Tooltip,
} from "antd";
import { connect } from "dva";
import { routerRedux } from "dva/router";
import moment from "moment";
import PropTypes from "prop-types";
import React, { PureComponent } from "react";
import enums from "../creditCar/enums";
import PateoAuthButtons from "@/common/PateoAuthButtons/PateoAuthButtons";
import Ellipsis from "@/components/Ellipsis";
import SearchAdtional from "../creditCar/component/searchAdtional/index";
import ExportTaskModal from "./exportTaskModal";
import FieldModal from "./fieldModal";
import styles from "./index.less";
import MsgRulerModal from "./msgRulerModal";
import RiskStatusModal from "../creditCar/riskStatusModal";
import DealerRiskManageModal from "../creditCar/dealRiskManageModal";
import { transferOption } from "@/utils/common";
import RiskLogModal from "../creditCar/riskLogModal";
import { getDicByKey, getDictOptionsByCode } from '@/support/common';
import { SettingOutlined } from '@ant-design/icons';
import MaskText from "@/components/MaskText";

const { Option } = Select;
// 下划线转驼峰
function toCamel(str) {
  return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
    return $1 + $2.toUpperCase();
  });
}
@connect((state) => ({
  menu: state.menu,
  abnormalCar: state.abnormalCar,
}))
export default class abnormalCar extends PureComponent {
  static contextTypes = {
    authButton: PropTypes.array,
    dicData: PropTypes.any,
  };

  state = {
    abnormalRiskControl:undefined,//风控异常时长
    riskStatus:undefined,//车辆风控状态
    vhlCurrentStatus: undefined,//实车当前状态
    creditType: undefined,
    creditTypeOptions: [],


    exportTaskVisible: false,
    riskEventList: [],
    // riskEventId: undefined,
    riskTriggerDate: undefined,
    vin: undefined,
    creditCompanyId: undefined,
    curPage: 1,
    pageSize: 10,
    total: 0,
    tableData: [],
    tableLoading: false,
    exportLoading: false,
    orgList: [],
    tboxRouseloading: false,
    tboxRouseCount: 35,

    tableColumns: [], //动态列表clonmn
    fieldList: [],
    visible: false,
    checked: [],
    columnsOptions: [], // 可以显示的字段
    fieldList: [], // 列表可显示动态字段
    fieldMore: [], // 更多筛选可以使用的字段
    fieldAdd: [], // 新增可用字段
    riskEventList: [],
    fieldColumns: [],
    currentSearchMode: "1",

    ruleList: [],
    msgRuleModalVisible: false,
    ruleListSelectedRecord: {},
    ruleListType: 1,

    riskvin: undefined,
    dealRiskManageModalVisible: false,
    riskLogModalVisible:false,//风控日志
    abnormalDurationStart: 0,//风控异常时长搜索天数
    abnormalDurationEnd: 0,
  };

  handleGetriskEventList = () => {
    this.props.dispatch({
      type: "abnormalCar/postObjWithRes",
      payload: {
        url: "/mscreditbusiness/event/page", 
        ...{
          curPage: 1,
          pageSize: 1000,
          enable: enums.riskEventEnable.effective.value,
        },
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          this.setState({
            riskEventList: response.data.rows,
          });
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  componentDidMount() {
    this.handleGetriskEventList();
    // this.handleTableData();
    this.getDic();
    this.handleTableNewData();
    this.handleGetSeriesByBrandCode();
    this.handleGetOrgList();
    this.getFieldList();
    this.handleGetFieldList();
    this.handleGetriskEventList();

  }
  getDic = () =>{
    const {menu: { dicData }} = this.props;
    const typeOption = getDictOptionsByCode(dicData, 'creditType');
    this.setState({
      creditTypeOptions: typeOption.map(e => ({
            label: e.label,
            value: e.value,
          })),
   })
  }
  addPreinstall = (columns) => {
    return columns.map((i) => {
      const sameTitle = columns.some(
        (j) => j.name === i.name && i.fieldId !== j.fieldId
      );
      if (sameTitle && i.fieldId) {
        i.name = `${i.name}(预设)`;
      }
      return i;
    });
  };
  getFieldList = () => {
    //获取列表字段
    this.props.dispatch({
      type: "abnormalCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/credit/merchant/field/scenelist?menu=riskcontrolvehicle&scene=list",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            let arr = [];
            this.addPreinstall(response.data).map((item) => {
              if (item.type === 4) {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (typeof text == "number") {
                      return text ? moment(text).format("YYYY-MM-DD") : "";
                    } else {
                      return text
                        ? moment(text, "YYYY-MM-DD").format("YYYY-MM-DD")
                        : "";
                    }
                  },
                });
              } else if (item.type === 5) {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (typeof text == "number") {
                      return text ? moment(text).format("HH:mm:ss") : "";
                    } else {
                      return text
                        ? moment(text, "HH:mm:ss").format("HH:mm:ss")
                        : "";
                    }
                  },
                });
              } else if (item.type === 6) {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (typeof text == "number") {
                      return text
                        ? moment(text).format("YYYY-MM-DD HH:mm:ss")
                        : "";
                    } else {
                      return text
                        ? moment(text, "YYYY-MM-DD HH:mm:ss").format(
                            "YYYY-MM-DD HH:mm:ss"
                          )
                        : "";
                    }
                  },
                });
              } else if (item.name === "是否支持跛行") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    return text == 1 ? "是" : "否";
                  },
                });
              } else if (item.name === "车辆预警状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == "0") {
                      return "未预警";
                    } else if (text == "1") {
                      return "预警";
                    } else {
                      return text;
                    }
                  },
                });
              } else if (item.name === "还款状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == "0") {
                      return "还款中";
                    } else if (text == "1") {
                      return "已逾期";
                    } else if (text == "2") {
                      return "已结清";
                    } else if (text == "3") {
                      return "融资已到期";
                    } else {
                      return "未知";
                    }
                  },
                });
              } else if (item.name === "车辆风控状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text, record) => {
                    if (text == 0) {
                      return "正常行驶"; 
                    } else if (text == 1) {
                      return "锁车"; 
                    } else if (text == 2) {
                      return "跛行"; 
                    } else {
                      return text;
                    }
                  },
                });
              } else if (item.name === "车机告警类型") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == 0) {
                      return "暂不支持";
                    } else if (text == 1) {
                      return "不可配置";
                    } else if (text == 2) {
                      return "可配置";
                    } else {
                      return text;
                    }
                  },
                });
              } else if (item.name === "车机告警状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == 0) {
                      return "正常";
                    } else if (text == 1) {
                      return "车机告警";
                    } else {
                      return ' ';
                    }
                  },
                });
              } else if (item.name === "实车当前状态") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text) => {
                    if (text == 0) {
                      return "正常";
                    } else if (text == 1) {
                      return "锁车";
                    } else if (text == 2) {
                      return "跛行";
                    } else if (text == 3) {
                      return "待车辆反馈";
                    } else {
                      return "待车辆反馈";
                    }
                  },
                });
              }else if (item.name === "授信类型") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: text => {
                    if (text == null) {
                      return '';
                    }
                    return getDicByKey(this.context.dicData, `creditType`, text.toString());
                  },
                });
              }else if (item.name === "经销商名称") {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                  render: (text, record) => {
                    if (text) {
                      return <a onClick={() => this.dealerRiskManage(record)}>{text}</a>;
                    } else {
                      return '';
                    }
                  },
                });
              } else {
                arr.push({
                  title: item.name,
                  dataIndex: toCamel(item.column),
                  key: toCamel(item.column),
                });
              }
            });
            arr = arr.map((i) => {
              i.columnShow = true;
              return i;
            });
            let enhanceData = this.fieldModal.getTableColumns(arr).map(item => {
              if(item.dataIndex === 'positionAddress') {
                return {
                  ...item,
                  render: (value) => {
                    return <MaskText text={value} type='location' />
                  }
                }
              }
              return item;
            })
            this.setState({
              tableColumns: enhanceData,
            });
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };
  openFieldModal = () => {
    this.fieldModal.open(this.state.tableColumns);
  };
  // 列表显示字段筛选方法
  filterColumns = (checkedValue) => {
    const { tableColumns } = this.state;
    const newColumns = [];
    console.log("选中要显示的列", checkedValue);
    console.log("目前的列", tableColumns);
    const value = [];
    checkedValue.forEach((e) => {
      value.push(toCamel(e));
    });
    tableColumns.map((item) => {
      if (value.includes(item.dataIndex)) {
        newColumns.push(item);
      }
    });
    // newColumns.push(tboxBtn);
    this.setState({
      tableColumns: newColumns,
      checked: checkedValue,
    });
  };

  handleGetFieldList = () => {
    this.props.dispatch({
      // 更多筛选数据
      type: "abnormalCar/postDataWithRes",
      payload: {
        url: "/mscreditbusiness/credit/merchant/field/scenelist?menu=riskcontrolvehicle&scene=more",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            this.setState({
              fieldMore: this.addPreinstall(response.data),
            });
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  handleGetSeriesByBrandCode = () => {
    this.props.dispatch({
      type: "abnormalCar/getDataWithRes",
      payload: { url: '/msdevice/base/vehicle/series/list' },
      callback: (response) => {
        this.setState({
          seriesList: response,
        });
      },
    });
  };
  handleTableNewData = () => {
    let params = [];
    const { curPage, pageSize, fieldColumns, currentSearchMode } = this.state;
    console.log(' currentSearchMode',  currentSearchMode)
    console.log('fieldColumns', fieldColumns)
    if (currentSearchMode == "1") {
      params = this.exChangeDefaultData().filter(
        (i) =>
          !(
            i.startVal === undefined ||
            i.startVal === null ||
            i.startVal === ""
          )
      );
    } else {
      params = fieldColumns;
    }
    console.log('consiftion', params);
    this.props.dispatch({
      type: "abnormalCar/postObjWithRes",
      payload: {
        url: "/vehicle/risk/error/page",
        curPage,
        pageSize,
        conditions: params,
        // businessCode: "warning",
      },
      callback: (response) => {
        if (response && response.statusCode == "0" && response.data) {
          if (
            response.data.rows.length === 0 &&
            response.data.pagination.current > 1
          ) {
            this.setState(
              {
                curPage: 1,
                pageSize: 10,
              },
              () => {
                this.handleTableNewData();
              }
            );
          } else {
            this.setState({
              tableData: response.data.rows,
              total: response.data.pagination.total,
            });
          }
        } else {
          if (response.statusCode !== "0") {
            // message.error(response.statusMessage);
          }
        }
        this.setState({
          tableLoading: false,
        });
      },
    });
  };
  loop = (arr) => {
    let tree= JSON.parse(JSON.stringify(arr))
      let newData = []
    const expanded = datas => {
      if (datas&& datas.length > 0){
        datas.forEach(e => {
          newData.push({sid: e.sid, name: e.orgName});
          expanded(e.children);
        })
      }
    };
    expanded(tree);
    return newData;
  }
  handleGetOrgList = () => {
    this.props.dispatch({
      type: "warningCar/getDataWithRes",
      payload: {
        url: "/org/tree",
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          if (response.data && response.data.length > 0) {
            const newData =  this.loop(response.data)
            this.setState({
              orgList: newData,
            });
          }
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  handleSearch = () => {
    this.handleTableNewData();
  };

  handleReset = () => {
    this.setState(
      {
        curPage: 1,
        pageSize: 10,
        vin: undefined,
        abnormalRiskControl:undefined,//风控异常时长
        riskStatus:undefined,//车辆风控状态
        vhlCurrentStatus: undefined,//实车当前状态
        // riskEventId: undefined,
        riskTriggerDate: undefined,
        creditCompanyId: undefined,
        fieldColumns: [],
        currentSearchMode: "1",
        creditType: undefined,
        abnormalDurationStart: 0,
        abnormalDurationEnd: 0,
      },
      () => {
        this.handleTableNewData();
        // this.SearchAdtionalRef.reset();
      }
    );
  };

  //点击导出异常车辆
  handleExportCar = (msg) => {
    this.setState({
      exportLoading: true,
    });
    let params = [];
    const { curPage, pageSize, fieldColumns, currentSearchMode } = this.state;
    if (currentSearchMode == "1") {
      params = this.exChangeDefaultData().filter(
        (i) =>
          !(
            i.startVal === undefined ||
            i.startVal === null ||
            i.startVal === ""
          )
      );
    } else {
      params = fieldColumns;
    }
    this.props.dispatch({
      type: "abnormalCar/postObjWithRes",
      payload: {
        url: "/vehicle/risk/error/exportQueryTask",
        conditions: params,
        curPage,
        pageSize,
      },
      callback: (response) => {
        if (response && response.statusCode == "0") {
          message.success("导出任务发送成功,请稍后查看");
        } else {
          // message.error(response.statusMessage);
        }
        this.setState({
          exportLoading: false,
        });
      },
    });
  };

  //点击导出任务
  handleExportTask = (msg) => {
    this.setState({
      exportTaskVisible: true,
    });
  };


  //点击详情
  handleDetail = (vin, record) => {
    sessionStorage.setItem("vin", vin);
    sessionStorage.setItem("detailInfo", JSON.stringify(record));
    sessionStorage.setItem("typeOption", JSON.stringify(this.state.creditTypeOptions));
    sessionStorage.setItem(
      "backPath",
      "/creditPlatform/abnormalCar"
    );
    this.props.dispatch(
      routerRedux.push({
        pathname:
          "/creditPlatform/abnormalCarDetail",
      })
    );
  };

  handleLocation = (vin) => {
    sessionStorage.setItem("vin", vin);
    sessionStorage.setItem("businessCode", "risk-error-log");
    sessionStorage.setItem(
      "abnormalCarLocationbackPath",
      "/creditPlatform/abnormalCar"
    );
    this.props.dispatch(
      routerRedux.push({
        pathname:
          "/creditPlatform/abnormalCarLocation",
      })
    );
  };
  changeExportTaskModalVisible = (flag) => {
    if (flag) {
      //TODO:请求接口刷新数据
      this.setState({
        exportTaskVisible: false,
      });
    } else {
      this.setState({
        exportTaskVisible: false,
      });
    }
  };
  // componentWillUnmount() {
  //   clearInterval(this.timer2);
  //   clearInterval(this.timer);
  // }
  specialDataGenrator = () => {
    // 生成特殊字段
    console.log(this.state.seriesList);
    return [
      {
        // 所属公司
        columnName: "vin",
        columnType: 1,
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
      {
        // 所属公司
        columnName: "company_name",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.orgList.map((i) => ({
            label: i.name,
            value: i.sid,
          })),
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
      {
        // 实车当前状态
        columnName: "vhl_current_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: "0",
              label: "正常",
            },
            {
              value: "1",
              label: "锁车",
            },
            {
              value: "2",
              label: "跛行",
            },
            {
              value: "3",
              label: "待车辆反馈",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        filterType: 1,
      },
      {
        // 车系
        columnName: "series_name",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.seriesList,
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
        // filterTypeLock: true,
        // defaultField: true,
      },
      {
        columnName: "last7_mileage",
        columnType: 3,
        filter: undefined,
        startVal: undefined,
        endVal: undefined,
        filterType: "1",
      },
      {
        columnName: "risk_event_content",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.riskEventList.map((i) => ({
            value: i.sid,
            label: i.riskEventContent,
          })),
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "limp_enable",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: "0",
              label: "不支持",
            },
            {
              value: "1",
              label: "支持",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "repayment_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 0-还款中；1-已逾期；2-已结清；3-融资已到期
              value: "0",
              label: "还款中",
            },
            {
              value: "1",
              label: "已逾期",
            },
            {
              value: "99",
              label: "未知",
            },
            {
              value: "2",
              label: "已结清",
              hideInOption: true,
            },
            {
              value: "3",
              label: "融资已到期",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "risk_warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              // 1：预警  0或null：未预警 ；
              value: "0",
              label: "未预警",
            },
            {
              value: "1",
              label: "预警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "warn_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "暂不支持",
            },
            {
              value: 1,
              label: "不可配置",
            },
            {
              value: 2,
              label: "可配置",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "warn_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              value: 0,
              label: "正常",
            },
            {
              value: 1,
              label: "车机告警",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "engine_state",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //  2-点火；0-熄火
              value: "0",
              label: "熄火",
            },
            {
              value: "2",
              label: "点火",
            },
            {
              value: "",
              label: "行驶中",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "risk_status",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: [
            {
              //   0-正常行驶，1-锁车，2-跛行
              value: "0",
              label: "正常行驶",
            },
            {
              value: "1",
              label: "锁车",
            },
            {
              value: "2",
              label: "跛行",
            },
          ],
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "credit_type",
        columnType: 2,
        extra: {
          selectType: 0,
          optionList: this.state.creditTypeOptions,
        },
        // filter: 9,
        startVal: undefined,
        endVal: undefined,
      },
      {
        columnName: "abnormal_risk_control",
        columnType: 3,
        filter: undefined,
        startVal: undefined,
        endVal: undefined,
        filterType: "1",
      }, 
    ];
  };

  exChangeDefaultData = () => {
    // 从外面带的属性
    const { vin, riskTriggerDate, creditCompanyId, creditType, abnormalRiskControl, riskStatus,vhlCurrentStatus, abnormalDurationStart,
      abnormalDurationEnd,} = this.state;
    console.log('vhlCurrentStatus', vhlCurrentStatus)
    return [
      {
        columnName: "vin",
        columnType: 1,
        filter: vin ? "1" : undefined,
        startVal: vin,
        endVal: undefined,
        filterType: "1",
      },
      //风控异常时长
      {
        columnName: "abnormal_risk_control",
        columnType: 3,
        filter: enums.comparison[abnormalRiskControl]
          ? enums.comparison[abnormalRiskControl].filter
          : undefined,
        startVal: abnormalRiskControl ? abnormalDurationStart : undefined,
        endVal: abnormalRiskControl ? abnormalDurationEnd : undefined,
        filterType: "1",
      },
      //车辆风控状态
      {
        columnName: "risk_status",
        columnType: 2,
        filter: riskStatus ? "9" : undefined,
        startVal: riskStatus,
        endVal: undefined,
        filterType: "1",
      },
      //实车当前状态
      {
        columnName: "vhl_current_status",
        columnType: 2,
        filter: vhlCurrentStatus ? "9" : undefined,
        startVal: vhlCurrentStatus,
        endVal: undefined,
        filterType: "1",
      },
      {
        columnName: "credit_type",
        columnType: 2,
        filter: creditType ? "9" : undefined,
        startVal: creditType? creditType : undefined,
        endVal: undefined,
        filterType: "1",
      },
    ];
  };
  handleOpenSeachModal = () => {
    // 更所筛选
    const specialData = this.specialDataGenrator(); // 特殊字段，本地定义
    let exChangeData = this.exChangeDefaultData(); // 从外面带进来的值
    this.SearchAdtionalRef.modalShow(specialData, exChangeData);
  };
  //点击经销商名称进入经销商风险管理页
  dealerRiskManage =(record)=>{
    const { dispatch } = this.props
    //获取当前经销商风险额度
    dispatch({
      type: 'abnormalCar/postDataWithRes',
      payload: {
        url: '/mscreditbusiness/dealer/limit/get',  //  查询高风险经销商额度
        orgId: record.orgId,
        dealerCode: record.dealerCode
      },
      callback: (res) => {
        const { statusCode, data } = res;
        if (statusCode === '0') {
          this.setState({
            dealRiskManageModalVisible: true
          });
          this.dealRiskModal.setData({...data})
        }
      },
    })
    this.setState({
      dealRiskManageModalVisible: true
    })
  }
   //行车轨迹
   handleTrack = (record) => {
    sessionStorage.setItem("abnormalCar_track_vin", record.vin);
    const { formValues, pageObj } = this.state;
    this.props.dispatch(
      routerRedux.push({
        pathname: "/creditPlatform/abnormalCarTrack",
        state: { pageObj, formValues },
      })
    );
  }
  //风控日志
  changeriskLogModalVisible = (flag) => {
    if (flag) {
      this.setState({
        riskLogModalVisible: false,
      });
    } else {
      this.setState({
        riskLogModalVisible: false,
      });
    }
  };
  handleRiskLog=(record)=>{
    this.setState({
      riskvin: record.vin,
      riskLogModalVisible: true,
    })
  }
  render() {
    const {
      abnormalRiskControl,
      riskStatus,
      vhlCurrentStatus,


      tableData,
      total,
      curPage,
      pageSize,
      tableLoading,
      exportTaskVisible,
      riskEventList,
      // riskEventId,
      riskTriggerDate,
      vin,
      exportLoading,
      creditCompanyId,
      orgList,
      tboxRouseloading,
      tboxRouseCount,
      fieldList,
      tableColumns,
      visible,
      checked,
      creditType,
      abnormalDurationStart,
      abnormalDurationEnd,
      riskLogModalVisible,
    } = this.state;
    const {menu: { permissions }} = this.props;
    const {location: { pathname }} = this.props;
    const locationBtnAuth = permissions.includes(pathname + '/' + 'abnormalCar_location');
    const trackBtnAuth = permissions.includes(pathname + '/' + 'abnormalCar_track');
    const detailBtnAuth = permissions.includes(pathname + '/' + 'abnormalCar_detail');
    const logBtnAuth = permissions.includes(pathname + '/' + 'abnormalCar_log');
    const oprationC = {
      title: "操作",
      dataIndex: "opt",
      fixed: "right",
      align: "center",
      filterDropdown: <div></div>,
      filterIcon: (
        <Tooltip placement="top" title="筛选">
        <SettingOutlined 
         style={{ marginLeft: 1 }}
         onClick={() => this.openFieldModal()}
        />
        </Tooltip>
      ), 
      render: (text, record) => {
        const btns = [];
        const detailBtn = {
          title: "详情",
          key: "detailBtn",
          onConfirm: () => this.handleDetail(record.vin, record),
        };
        const locationBtn = {
          title: "查看定位",
          key: "location",
          onConfirm: () => this.handleLocation(record.vin),
        };
        const pathBtn = {
          title: "行车轨迹",
          key: "pathBtn",
          onConfirm: () => this.handleTrack(record),
        };
        const riskLogBtn = {//若手动或自动实施锁车/解除锁车/跛行/解除跛行后，则显示风控日志按钮
          title: "风控日志",
          key: "riskLogBtn",
          onConfirm: () => this.handleRiskLog(record),
        };
        if (detailBtnAuth) btns.push(detailBtn);
        if (logBtnAuth) btns.push(riskLogBtn);
        if (trackBtnAuth) btns.push(pathBtn);
        if (locationBtnAuth) btns.push(locationBtn);
        return (
          <PateoAuthButtons
            authStr="abnormalCar"
            btns={btns}
          />
        );
      },
    };

    const pagination = {
      showSizeChanger: true,
      total: total,
      current: curPage,
      pageSize: pageSize,
      showTotal: () => {
        return <span>共&nbsp;{total}&nbsp;条</span>;
      },
    };
    const tableProps = {
      // columns,
      columns: tableColumns.filter((i) => i.columnShow).concat([oprationC]),
      pagination,
      rowKey: "sid",
      scroll: { x: "max-content" },
      loading: tableLoading,
      dataSource: tableData,
      onChange: (pagination) => {
        this.setState(
          {
            curPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          () => {
            this.handleTableNewData();
          }
        );
      },
    };
    const exportCarBtnAuth = permissions.includes(pathname + '/' + 'abnormalCar_exportCar');
    const exportTaskBtnAuth = permissions.includes(pathname + '/' + 'abnormalCar_exportTask');
    const riskStatusOptions = [
      {
        label: "正常行驶",
        value: "0",
      },
      {
        label: "锁车",
        value: "1",
      },
      {
        label: "跛行",
        value: "2",
      },
    ];
    const vehicleStatusOptions = [
      {
        label: "正常",
        value: "0",
      },
      {
        label: "锁车",
        value: "1",
      },
      {
        label: "跛行",
        value: "2",
      },
      {
        label: "待车辆反馈",
        value: "3",
      },
    ];
    return (
      <Spin
        spinning={tboxRouseloading}
        size="large"
        tip={`Loading(${tboxRouseCount})s`}
      >
        <div>
          <div className={styles.pateoSearch}>
            <div className={styles.searchInputStr}>
              <div className={styles.title}>VIN号:</div>
              <Input
                placeholder="请输入vin号"
                value={vin}
                onChange={(e) => {
                  this.setState({
                    vin: e.target.value,
                  });
                }}
              />
            </div>
            <div className={styles.searchInputStr}>
              <div className={styles.title}>风控异常时长:</div>
              <Select
                placeholder="请选择"
                value={abnormalRiskControl}
                onChange={(e) => {
                  this.setState({
                    abnormalRiskControl: e,
                    abnormalDurationStart: 0,
                    abnormalDurationEnd: 0,
                  });
                }}
              >
                {enums.comparison.array.map((option) => {
                  return (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  );
                })}
              </Select>
              {enums.comparison.gt.value === abnormalRiskControl ? (
                <InputNumber
                  placeholder="请输入"
                  onChange={(e) => {
                    this.setState({
                      abnormalDurationStart: e || 0,
                    });
                  }}
                  value={abnormalDurationStart}
                  min={0}
                />
              ) : null}
              {enums.comparison.between.value === abnormalRiskControl ? (
                <>
                  <InputNumber
                    placeholder="请输入"
                    onChange={(e) => {
                      this.setState({
                        abnormalDurationStart: e || 0,
                      });
                    }}
                    value={abnormalDurationStart}
                    min={0}
                  />
                  <InputNumber
                    placeholder="请输入"
                    onChange={(e) => {
                      this.setState({
                        abnormalDurationEnd: e || 0,
                      });
                    }}
                    value={abnormalDurationEnd}
                    min={0}
                  />
                </>
              ) : null}
              {enums.comparison.lt.value === abnormalRiskControl ? (
                <InputNumber
                  placeholder="请输入"
                  onChange={(e) => {
                    this.setState({
                      abnormalDurationStart: e || 0,
                    });
                  }}
                  value={abnormalDurationStart}
                  min={0}
                />
              ) : null}
            </div>
            <div className={styles.searchInputStr}>
              <div className={styles.title}>车辆风控状态:</div>
              <Select
                value={riskStatus}
                placeholder="请选择车辆风控状态"
                onChange={(e) => {
                  this.setState({
                    riskStatus: e,
                  });
                }}
              >
                {riskStatusOptions.map((e) => {
                  return (
                    <Option key={e.value} value={e.value}>
                      {e.label}
                    </Option>
                  );
                })}
              </Select>
            </div>
            <div className={styles.searchInputStr}>
              <div className={styles.title}>实车当前状态:</div>
              <Select
                value={vhlCurrentStatus}
                placeholder="请选择实车当前状态"
                onChange={(e) => {
                  this.setState({
                    vhlCurrentStatus: e,
                  });
                }}
              >
                {vehicleStatusOptions.map((e) => {
                  return (
                    <Option key={e.value} value={e.value}>
                      {e.label}
                    </Option>
                  );
                })}
              </Select>
            </div>
            <div className={styles.searchInputStr}>
              <div className={styles.title}>授信类型:</div>
              <Select
                value={creditType}
                placeholder="请选择授信类型"
                onChange={(e) => {
                  this.setState({
                    creditType: e,
                  });
                }}
              >
                  {transferOption(this.state.creditTypeOptions, ["value","label"])}
              </Select>
            </div>
            <div className={styles.searchBtn}>
              <Button
                style={{ marginRight: "10px" }}
                onClick={() => this.handleOpenSeachModal()}
              >
                更多筛选条件
              </Button>
              <Button
                onClick={() => this.handleSearch()}
                type={"primary"}
                style={{ marginRight: "10px" }}
              >
                查询
              </Button>
              <Button onClick={() => this.handleReset()}>重置</Button>
            </div>
          </div>
          <div className={styles.pateoBtns}>
            {exportCarBtnAuth ? (
              <div className={styles.btnItem}>
                <Button
                  type="primary"
                  loading={exportLoading}
                  onClick={() => this.handleExportCar()}
                >
                  导出风控异常车辆
                </Button>
              </div>
            ) : null}
            {exportTaskBtnAuth ? (
              <div className={styles.btnItem}>
                <Button type="primary" onClick={() => this.handleExportTask()}>
                  导出任务
                </Button>
              </div>
            ) : null}
          </div>

          <Card bordered={false} style={{ marginTop: 10 }}>
            <Table {...tableProps} />
          </Card>
          {exportTaskVisible ? (
            <ExportTaskModal
              changeExportTaskModalVisible={this.changeExportTaskModalVisible}
            />
          ) : null}
          <FieldModal
            onRef={(fieldModal) => (this.fieldModal = fieldModal)}
            fieldName="abnormal"
            dispatch={this.props.dispatch}
            onSubmit={(tableColumns) => {
              this.setState({
                tableColumns,
              });
            }}
            tableColumns={tableColumns}
          />

          <SearchAdtional
            onRef={(ref) => (this.SearchAdtionalRef = ref)} // ref赋值
            SearchAdtionalOptions={this.state.fieldMore} // 可选字段
            fieldName="abnormal"
            handleSubmit={(columns) => {
              // 点击确认搜索
              this.setState(
                {
                  fieldColumns: columns,
                  currentSearchMode: "2",
                },
                () => {
                  this.handleTableNewData();
                }
              );
            }}
          ></SearchAdtional>

          {this.state.msgRuleModalVisible && (
            <MsgRulerModal
              changeVisible={() => {
                this.setState({ msgRuleModalVisible: false });
                // this.handleTableNewData();
              }}
              onOk={() => {
                this.setState({ msgRuleModalVisible: false });
                this.handleTableNewData();
              }}
              businessCode="risk-error-log"
              visible={this.state.msgRuleModalVisible}
              ruleList={this.state.ruleList}
              record={this.state.ruleListSelectedRecord}
              dispatch={this.props.dispatch}
              ruleListType={this.state.ruleListType}
            />
          )}
          <DealerRiskManageModal
           changeVisible={() => {
            this.setState({ dealRiskManageModalVisible: false });
          }}
             modalVisible={this.state.dealRiskManageModalVisible}
             onRef={(dealRiskModal) => (this.dealRiskModal = dealRiskModal)}
            dispatch={this.props.dispatch}
          />
         {riskLogModalVisible ? (<RiskLogModal
            changeriskLogModalVisible={this.changeriskLogModalVisible}
            riskvin={this.state.riskvin}
          />) :null}
        </div>
      </Spin>
    );
  }
}
